package com.lq.javawebTest.core;

import com.lq.javawebTest.core.entity.Session;
import com.lq.javawebTest.core.inter.Filter;
import com.lq.javawebTest.core.inter.Servlet;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

public class Container {
    /**
     * 存放了大量的uri和servlet的对应关系
     */
    //而Servlet实例对象我们是从ServletContainer容器中去拿的，也就是懒加载
    private static final ServletContainer SERVLETS = new ServletContainer();

    /**
     * 每一个客户端的Session数据
     */
    private static final Map<String, Session> SESSIONS = new ConcurrentHashMap<>(8);

    /**
     * 存放过滤器,这个没有必要实现懒加载，需要全部加载
     * @param uri
     * @return
     */
    private static final List<Filter> FILTERS = new CopyOnWriteArrayList<>();
    //初始化filters
    static{
        List<String> filters = Configuration.getFilters();
        for(String fil : filters){
            try {
                Filter filter = (Filter)Class.forName(fil).newInstance();
                FILTERS.add(filter);
            } catch (InstantiationException e) {
                throw new RuntimeException(e);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            } catch (ClassNotFoundException e) {
                throw new RuntimeException(e);
            }

        }
    }


    public static Servlet getServlet(String uri){
        return SERVLETS.get(uri);
    }

    public static void addSession(String key, Session session){
        SESSIONS.put(key, session);
    }

    public static Session getSession(String key){
        return SESSIONS.get(key);
    }

    public static List<Filter> getFilters(){
        return FILTERS;
    }
}
